package com.sinocare.project.common.util;

import com.sinocare.project.common.entity.SncUserLogin;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

import java.util.Random;
/**
 * MD5加密工具类
 */
public class SaltUtil {
    /**/
    // 加密形式
    public static final String ALGORITHM_NAME = "MD5";
    // 加密次数（随机,最小124）
    private static final int HASH_ITERATIONS = new Random().nextInt(1024) + 124;

    /**
     * 返回根据随机盐值和随机散列次数MD5加密后的字符串
     *
     * @param user user对象
     * @param salt 盐值
     * @return 密码
     */
    public static String getPassword(SncUserLogin user, String salt) {
        return new SimpleHash(ALGORITHM_NAME, user.getPassword(), ByteSource.Util.bytes(salt), HASH_ITERATIONS).toHex();
    }
    /**
     * 返回根据传入数据加密后的密码
     * @param password 需要加密的密码
     * @param salt  加密盐值
     * @param i 散列次数
     * @return
     */

    public static String getPassword(String password, String salt, Integer i) {
        return new SimpleHash(ALGORITHM_NAME, password, ByteSource.Util.bytes(salt+","+i), i).toHex();
    }

    /**
     * @param user 密码加密后的user对象
     * @param i    随机生成的盐值的长度
     * @return User
     */
    public static SncUserLogin encryptPassword(SncUserLogin user, Integer i) {
        String saltA = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ~!@#$%^&*()<>?";
        StringBuilder salt = new StringBuilder();
        char[] chars = saltA.toCharArray();
        for (int j = 0; j < i; j++) {
            int o = new Random().nextInt(chars.length);
            salt.append(chars[o]);
        }
        salt.append(","+HASH_ITERATIONS);//asf,123
        user.setPassword(getPassword(user, salt.toString())+","+salt);
        return user;
    }

    public static void main(String[] args) {

        SncUserLogin sncUserLogin = new SncUserLogin();
        sncUserLogin.setPassword("123456");
        SncUserLogin sncUserLogin1 = SaltUtil.encryptPassword(sncUserLogin, 5);
        System.out.println(sncUserLogin1.getPassword());
//        String[] salt = "c48e1f6a9c81301ac567bb68d6339a0b,q*sf<,251".split(",");
//        String password = SaltUtil.getPassword("123456", salt[1], Integer.parseInt(salt[2]));
//        System.out.println(password);
    }
}
